package jdk.thread.threadpool;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工厂类，可调用的方法和自定义需要实现的方法就一个newThread(Runnable),
 * 调用newThread创建新线程时，需要传入Runnable实现，就是说新线程的run方法执行主体是由外部指定的，
 * 工厂类只是可以定制一些环绕在run()边的操作，如执行run()前后添加输出信息。
 */
public class ThreadFactoryTest {

    public static void main(String[] args) {
        ThreadFactory myFactory = new MyFactory("LUOBINJIE");

        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("获取随机数"+ RandomUtil.randomInt(0, 1000));
            }
        };

        myFactory.newThread(r).start();
        myFactory.newThread(r).start();
    }
}

class MyFactory implements ThreadFactory{

    AtomicInteger i = new AtomicInteger();
    String threadPrefix;

    public MyFactory(String threadPrefix){
        this.threadPrefix = threadPrefix;
    }

    @Override
    public Thread newThread(Runnable r) {
        return new FactoryThread(threadPrefix+"-"+i.incrementAndGet(), r);
    }

    class FactoryThread extends Thread{

        String name;
        Runnable runnable;

        public FactoryThread(String name, Runnable runnable) {
            this.name = name;
            this.runnable = runnable;
        }

        @Override
        public void run() {
            synchronized (runnable) {
                System.out.println("========线程" + name + "开始执行！！====");
                runnable.run();
                System.out.println("========线程" + name + "结束执行！！====");
            }
        }
    }
}
